package org.thingsboard.server.utils;

import com.google.gson.JsonObject;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

public class HttpUtil {
    public static String doPost(String url, JsonObject param) {
        System.out.println("推送数据: "+param.toString());
        HttpPost httpPost = null;
        String result = null;
        HttpClient client = new DefaultHttpClient();
        try {
            httpPost = new HttpPost(url);
            if (param != null) {
                StringEntity se = new StringEntity(param.toString(), "utf-8");
                httpPost.setEntity(se); // post方法中，加入json数据
                httpPost.setHeader("Content-Type", "application/json");
                httpPost.addHeader("referer","http://localhost");
            }
            HttpResponse response = client.execute(httpPost);
            if (response != null) {
                HttpEntity resEntity = response.getEntity();
                if (resEntity != null) {
                    result = EntityUtils.toString(resEntity, "utf-8");
                    System.out.println("事件推送结果: "+result);
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }finally{
            httpPost.releaseConnection();
        }
        return result;
    }

    public static void main(String[] args) {
        JsonObject jsonObject=new JsonObject();
        jsonObject.addProperty("test","test");
        doPost("http://192.168.0.102:7002/zhjs/webService/fromIto/setEvent",jsonObject);
    }
}
